<template>
<div>
  <transition name="el-fade-in-linear">
    <div v-if="showType == 'list'" class="advance-query-form">
      <el-tabs v-model="activeName" @tab-click="handleClick" class="infoTabStyle">
        <el-tab-pane label="全部" name="-1"></el-tab-pane>
        <el-tab-pane :label="item.statusName" :name="item.status.toString()" v-for="(item,index) in statusList"></el-tab-pane>
      </el-tabs>
      <TableList :status="activeName" ref="table" :statusList="statusList" :serveCategoryList="serveCategoryList" :projectList="projectList" v-if="activeName" @onAdd="onAdd" @handleEdit="onEdit" @handleDetail="onDetail"></TableList>
    </div>
  </transition>
  <transition name="el-fade-in-linear">
    <div class="form-single-fragment" style="position: relative" v-if="showType == 'form'">
      <header-handle :headerContent="headerContent" :buttons="formStatus != 'show' ? handleButtons : shareBtn" @goBack="goBack"></header-handle>
      <el-divider class="mt0 mb12"></el-divider>
      <FormDetail :initData="initActivityData" ref="activityRef" :formStatus="formStatus" :initForm="editFormData"></FormDetail>
      <el-dialog :visible.sync="dialogTableVisible" width="300px">
        <div class="popups" id="qrcode">
          <!-- <vue-qr :text="setQRCodeUrl()" :size="200"></vue-qr> -->
          <img :src="QRImgUrl" />
          <el-button type="text" @click="downQRCode" size="middle" class='downCodeBtn'>下载二维码</el-button>
        </div>
      </el-dialog>
    </div>
  </transition>
</div>
</template>

<script>
import TableList from './table/index.vue'
import FormDetail from './form/index.vue'
import QRCode from "qrcode";
import {
  ActivityController,
  DictionaryController,
  ProjectController
}
from '@/api';
export default {
  name: "volunActivies",
  components: {
    TableList,
    FormDetail
  },
  data() {
    return {
      activeName: '-1',
      statusList: [],
      showType: 'list',
      serveCategoryList: [],
      projectList: [],
      editFormData: {},
      formStatus: "",
      headerContent: "",
      handleButtons: [{
          status: 1,
          label: '取消',
          method: () => {
            this.goBack();
          },
        }, {
          status: 1,
          label: '分享',
          method: () => {
            this.shareCode();
          },
        },
        {
          type: 'primary',
          status: 1,
          label: '确定',
          method: () => {
            this.onConfirm();
          },
        }
      ],
      shareBtn: [{
        status: 1,
        label: '分享',
        method: () => {
          this.shareCode();
        },
      }],
      initActivityData: {
        serveCategory: {
          dropdownList: []
        },
        projectId: {
          dropdownList: []
        },
        serveTarget: {
          dropdownList: []
        },
        area: {
          areaOptions: JSON.parse(sessionStorage.getItem("areaOptions4"))
        }
      },
      dialogTableVisible: false,
      QRImgUrl: ""
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      let me = this;
      ActivityController.status(this, {
        dto: {}
      }).then(res => {
        me.statusList = res.data;
      }).catch(err => {
        me.$message.error(err)
      })
      me.getDicData('ServerCategory', (data) => {
        me.initActivityData.serveCategory.dropdownList = data
      })
      me.getDicData('ServerTarget', (data) => {
        me.initActivityData.serveTarget.dropdownList = data
        me.serveCategoryList = data;
      })
      me.loadProject()
    },
    getDicData(code, callBack) {
      let params = {};
      params.dictCode = code;
      DictionaryController.dictGlobalDict(this, params).then(res => {
        callBack(res.getList())
      })
    },
    loadProject() {
      let params = {};
      params.condition = {};
      ProjectController.list(this, params).then(res => {
        this.initActivityData.projectId.dropdownList = res.data.dataList;
        this.projectList = res.data.dataList
      }).catch(e => {
        me.$message.error(e)
      });
    },
    handleClick() {
      this.$nextTick(() => {
        this.$refs.table.refreshActivities(false);
      })

    },
    onAdd() {
      this.formStatus = "add";
      this.showType = "form";
      this.editFormData = {};
      this.headerContent = "新建活动"
    },
    onEdit(val) {
      this.formStatus = "edit";
      this.editFormData = val;
      this.showType = "form";
      this.headerContent = "编辑活动"
    },
    onDetail(val) {
      this.formStatus = "show";
      this.editFormData = val;
      this.showType = "form";
      this.headerContent = "查看活动"
    },
    goBack() {
      this.showType = 'list'
    },
    onConfirm() {
      let me = this;
      let length = Object.values(me.$refs.activityRef.getFormData()).length;
      if (length > 0) {
        let data = JSON.parse(JSON.stringify(me.$refs.activityRef.getFormData()))
        data.startDate = data.date[0]
        data.endDate = data.date[1]
        me.$delete(data, "date")
        if (data.area?.length > 0) {
          let arr = data.area;
          data.province = arr[0];
          data.city = arr[1];
          data.district = arr[2];
          data.street = arr[3]
        }
        me.$delete(data, "area")
        ActivityController.add(me, data).then(res => {
          me.$message.success("保存成功")
          me.showType = 'list'
        })
      }
    },
    downQRCode() {
      const fileName = 'activity.png'
      let img = document.getElementById('qrcode').getElementsByTagName('img')[0].src
      let aLink = document.createElement('a')
      let blob = this.base64ToBlob(img)
      let evt = document.createEvent("HTMLEvents")
      evt.initEvent("click", true, true) // initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
      aLink.download = fileName
      aLink.href = URL.createObjectURL(blob);
      aLink.click()
    },
    base64ToBlob(code) {
      let parts = code.split(';base64,')
      let contentType = parts[0].split(':')[1]
      let raw = window.atob(parts[1])
      let rawLength = raw.length
      let uInt8Array = new Uint8Array(rawLength)
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i)
      }
      return new Blob([uInt8Array], {
        type: contentType
      })
    },
    shareCode() {
      let me = this;
      if (me.editFormData.activityId) {
        let opts = {
          errorCorrectionLevel: "L", //容错级别
          type: "image/png", //生成的二维码类型
          quality: 0.3, //二维码质量
          margin: 4, //二维码留白边距
          width: 1280, //宽
          height: 1280, //高
          text: "", //二维码内容
          color: {
            dark: "#666666", //前景色
            light: "#fff", //背景色
          },
        };
        let str = "https://wmsj.1000best.cn/qrcode/activity?activityId=" + me.editFormData.activityId;
        QRCode.toDataURL(str, opts, (err, url) => {
          if (err) throw err;
          me.QRImgUrl = url;
          me.dialogTableVisible = true;
        });
      } else {
        me.$message.warning("暂无详情")
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.infoTabStyle {
    background-color: white;
    // padding: 0 20px;
}
</style>
